package com.jml.zookeeper.一期.zookeeper分布式锁;

// 使用多线程模拟生成订单号,有多个订单重复
public class ZKOrderService implements Runnable {
    private OrderNumGenerator orderNumGenerator = new OrderNumGenerator();

    // 每一个任务都创建了ZookeeperDistrbuteLock类，所以里面的CountDownLatch不是共用的，所以CountDownLatch不会存在线程安全的问题
    private ZKLock lock = new ZookeeperDistrbuteLock();

    @Override
    public void run() {
        getNumber();
    }

    public void getNumber() {

        String number = null;
        try {
            lock.getLock();
            number = orderNumGenerator.getNumber();
            System.out.println(Thread.currentThread().getName() + ",生成订单ID:" + number);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unLock();

        }
    }

    public static void main(String[] args) {
        System.out.println("####生成唯一订单号###");
        for (int i = 0; i < 100; i++) {
            new Thread(new ZKOrderService()).start();
        }

    }
}
